package com.woniu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.user.controller.form.RemarkForm;
import com.woniu.user.exception.WebException;
import com.woniu.user.exception.WebExceptionCode;
import com.woniu.user.model.Account;
import com.woniu.user.model.Order;
import com.woniu.user.model.Remark;
import com.woniu.user.dao.RemarkDao;
import com.woniu.user.service.AccountService;
import com.woniu.user.service.OrderService;
import com.woniu.user.service.RemarkService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.user.util.BeanCopyUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.beans.beancontext.BeanContext;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Silas
 * @since 2023-02-15
 */
@Service
public class RemarkServiceImpl extends ServiceImpl<RemarkDao, Remark> implements RemarkService {

    @Resource
    private AccountService accountService;

    @Resource
    private OrderService orderService;

    // 新增评价
    @Override
    public void add(Integer userId, RemarkForm form) {
        Account account = accountService.getById(userId);
        if (account == null) throw new WebException(WebExceptionCode.USER_IS_NOT_EXISTS);
        // 获取订单信息
        Integer orderId = form.getOrderId();
        Order order = orderService.getById(orderId);
        // 生成评价对象
        Remark remark = BeanCopyUtil.copyObject(order, Remark.class);
        remark.setScore((double)form.getScore());
        remark.setContent(form.getContent());
        this.save(remark);
    }

    @Override
    public Remark get(Integer userId, Integer orderId) {
        Account account = accountService.getById(userId);
        if (account == null) throw new WebException(WebExceptionCode.USER_IS_NOT_EXISTS);
        Remark remark = this.getOne(new QueryWrapper<Remark>().eq("order_id", orderId).eq("user_id", userId));
        if(remark == null) throw new WebException(WebExceptionCode.REMARK_IS_NULL);
        return remark;
    }
}
